/**
* @description: 标准化作业--执行
* @author: yaochao
* @data:2023年6月12日
* @remark:
**/
<template>
	<view class="content">
		<nav-bar class="header" :background="backgroundColor" back :title="title" @goBack="goBack">
			<!-- <text class="save_btn" slot="scan" @click="goSave">保存</text> -->
		</nav-bar>

		<view class="container" v-if="surveyArr.length>0">
			<div id="directory" class="directory" ref="wrapper" v-if="recordData.length>0">
				<ul :class="isExpand?'expand-ul':''" ref="scroller">
					<li :class="[{'active': curSort==item.sort}, 'li-number']"
						:style="{'backgroundColor':libgColor[item.isExecute]}" @click="handleSelectLi(item)"
						v-for="(item, index) in recordData" :key="index">
						{{item.sort}}
					</li>
				</ul>
				<view class="expand-wrap">
					<van-icon :name="isExpand?'arrow-up':'arrow-down'" @click="toggleArrow" />
				</view>
			</div>
			<view class="title">
				<span class="t-number">{{curSort}}</span> {{curSurveyObj}}
			</view>
			<view class="card">
				<view class="card-wrap" v-for="(item, index) in surveyArr" :key="index">
					<view class="w-row-1">
						<view class="row-l">
							<!-- <img src="../../../static/standardizedOperationImg/zxckBlue.png" class="icon"> -->
							<span>{{item.surveyContent}}</span>
						</view>
						<van-radio-group v-model="item.isStandard" direction="horizontal"
							@change="standardChange($event,item)">
							<van-radio :name="0">标准</van-radio>
							<van-radio :name="1">非标</van-radio>
						</van-radio-group>
					</view>
					<view class="w-row-2">
						<view class="r-l">标准结果：<span>{{item.standardResult}}</span></view>
						<view class="r-r">等级：<span>{{item.surveyLevel}}级</span></view>
					</view>
					<view class="w-row-3">
						风险点：{{item.pointRisks}}<br />
						现场预控技术措施：{{item.technicalMeasures}}
					</view>
					<view class="w-row-4">
						<view class="r-4-label isrequired">现场照片:<span>（最多上传3张）</span></view>
						<view class="image-wrap">
							<view class="image-list">
								<view class="upload-button" v-for="(imgItem, idx) in item.file" :key="idx">
									<view v-if="imgItem.img" class="delete-icon"
										@click.stop="imageHandle(idx,imgItem, 'DELETE',index)">
										×</view>
									<img v-if="imgItem.img" :src="imgItem.img" alt=""
										@click.stop="imageHandle(idx,imgItem, 'PREVIEW', index)">

								</view>
								<img v-if="item.file.length < wxCount" src="../../../static/img/ywgj.png" alt=""
									@click.stop="imageHandle(0,null, 'CHOOSE', index)">
							</view>
						</view>
					</view>
					<view class="w-row-5" v-if="item.isStandard">
						<view class="r-5-label isrequired">现场落地情况说明</view>
						<textarea class="r-5-remark" v-model="item.situationDescription" placeholder="情况说明" />
					</view>
				</view>
			</view>
		</view>
		<view class="sub-btn-container">
			<van-button class="submit-btn" block type="info" :disabled="!submintStatus" color="#417ADC"
				@click="executeSubmit">保存{{curSort < recordData.length?'，下一项':''}}
			</van-button>
			<!-- <van-button class="submit-btn" block type="info" :disabled="!submintStatus" color="#417ADC">提交</van-button> -->
		</view>
		<van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
			<van-swipe>
				<div v-for="(image, index) in fileList" :key="index">
					<van-swipe-item v-if="image" style="text-align: center;">
						<img :src="image.img" />
					</van-swipe-item>
				</div>
			</van-swipe>
		</van-popup>
	</view>
</template>
<script>
	import navBar from '../../../components/common/nav-bar'
	import wx from '../../../static/common_js/jweixin_1.0.0'
	import {
		debounce
	} from '../../../utils/index'
	import {
		Dialog,
		Toast
	} from 'vant'
	import axios from 'axios'
	import {
		mapGetters
	} from 'vuex'
	import baseConfig from '../../../common/config'
	let config = {}
	baseConfig.getOptions.then(res => {
		config = res
	})
	export default {
		name: 'index',
		components: {
			navBar
		},
		props: {},
		data() {
			return {
				baseUrl: "",
				backgroundColor: '#417ADC',
				title: '执行',
				workId: '',
				// submintStatus: true,
				curSort: 1,
				curSurveyObj: '',
				allSurverData: [],
				recordData: [],
				surveyIndex: 0,
				surveyArr: [],
				isExpand: false,
				libgColor: {
					0: '#C9C9C9', // 未完成
					1: '#3CDA68' // 已完成
				},
				selectIndex: 0, //用于移动到下一项作业
				fileList: [], //图片预览信息
				showPreview: false, //图片预览
				wxCount: 3, //相册可选取数量，默认3张
				base64List: [], //相册文件数据
			}
		},
		computed: {
			...mapGetters(['userData']),
			submintStatus: function() {
				if (this.surveyArr.length > 0) {
					let imgStatus = []
					let textStatus = []
					this.surveyArr.forEach(item => {
						if (item.isStandard === 1 && !item.situationDescription) {
							textStatus.push(item.isStandard)
						}
						let isImg = true
						if (item.file.length > 0) {
							item.file.map(fileItem => {
								if (fileItem.img) {
									isImg = false
								}
							})
						}
						imgStatus.push(isImg ? 0 : 1)
					})
					return !imgStatus.includes(0) && textStatus.length === 0
				}
			}
		},
		watch: {},
		mounted() {},
		onLoad(option) {
			this.workId = option.id
			this.getSurverData()
			this.baseUrl = config.firstUrl
			// this.baseUrl = `http://${this.$apiRequest.bzhzyApi.fileUrl}`
		},
		methods: {
			goBack() {
				uni.navigateBack()
			},
			/**
			 * 通知上一个页面刷新数据
			 */
			back() {
				let pages = getCurrentPages()
				let prevPage = pages[pages.length - 2] //上一个页面
				prevPage.isRefresh = true
				uni.navigateBack()
			},
			getSurverData() {
				this.$apiRequest.bzhzyApi
					.getSurverExecutionInfo({
						userId: this.userData.userId,
						workPlanId: this.workId
					})
					.then(res => {
						this.allSurverData = res.data
						this.recordData = this.genRecord(res.data)
						this.handleSelectLi(this.recordData[this.selectIndex])
					})
			},
			genRecord(arr) {
				let newArr = []
				if (arr && arr.length > 0) {
					arr.forEach(item => {
						newArr.push({
							sort: item.sort,
							isExecute: item.isExecute,
							objId: item.objId
						})
					})
				}
				return newArr
			},
			selectCurItem() {
				if (this.allSurverData && this.allSurverData.length > 0) {
					this.allSurverData.filter(item => {
						if (item.sort === this.curSort) {
							this.curSurveyObj = item.surveyObj
							this.surveyArr = item.child.map(childItem => {
								let isImg = false
								childItem.file.map(fileItem => {
									fileItem["img"] = fileItem.img ? fileItem.img : (fileItem
										.filePath ? this.baseUrl + fileItem
										.filePath : null)
									fileItem["raw "] = fileItem.raw ? fileItem.raw : null
									fileItem["type"] = ''
									if (!fileItem.filePath) {
										isImg = true
									}
									return fileItem
								})
								return childItem
							})
						}
						return item
					})
				}
			},
			/**
			 * 子项目切换
			 * @param {Object} e
			 */
			handleSelectLi(e) {
				this.curSort = e.sort
				this.selectCurItem()
			},
			/**
			 * 标准/非标change
			 * 非标切换为标准后，清空现场落地情况说明
			 */
			standardChange(data, item) {
				item.situationDescription = item.isStandard !== 1 ? "" : item.situationDescription
			},
			toggleArrow() {
				this.isExpand = !this.isExpand
			},
			goSave() {
				this.$apiRequest.bzhzyApi.executeSubmitLogic({
					workPlanId: this.workId
				}).then(res => {
					Toast(res.msg)
					this.back()
				}).catch(error => {
					Toast(error)
				})
			},
			/**
			 * 删除文件接口，当每一项数据的三张图片删全部除，需要改为未提交状态（现阶段请求接口）
			 * @param {Object} fileData
			 */
			deleteFile(fileData, index, imgIndex) {
				this.$apiRequest.bzhzyApi.delFileInfo({
					fileId: fileData.fileId,
					operatingItem: fileData.operatingItem
				}).then(res => {
					Toast(res.msg)
					this.surveyArr[index].file.splice(imgIndex, 1)

					// let index = this.recordData.findIndex(item => item.sort === this.curSort)
					// this.selectIndex = index
					// this.getSurverData()
				})
			},
			handleDebGet: debounce(function() {
				let formData = new FormData()
				let isFile = false //上传数据是否包含文件，不包含不走文件接口
				this.surveyArr.forEach((item, index) => {
					let fileNum = []
					item.file.forEach(fileItem => {
						if (fileItem.raw) {
							fileNum.push(fileItem)
						}
					})
					if (fileNum.length > 0) {
						item.file.map(e => {
							if (e.raw) {
								formData.append(`model[${index}].files`, e.raw)
								isFile = true
							}
						})
						formData.append(`model[${index}].fileClass`, 1)
						formData.append(`model[${index}].workPlanId`, item.workPlanId)
						formData.append(`model[${index}].operatingItem`, item.objId)
					}
				})
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data',
						Authorization: uni.getStorageSync('token') || ''
					}
				}
				let url = ''
				// #ifndef IGW
				url = '/ap/bzzy/web/work/uploads'
				// #endif
				// #ifdef IGW
				url = `${this.baseUrl}/bzzy/web/work/uploads`
				// #endif

				
				// url = `http://${this.$apiRequest.bzhzyApi.fileUrl}/bzzy/web/work/uploads`
				
				//无文件不走上传文件接口
				if (!isFile) {
					this.postMessage()
					return
				}
				axios.post(url, formData, config).then(res => {
					if (res.data.code == 0) {
						this.postMessage()
					} else if (res.data.code == 401) {
						Dialog.alert({
							message: "当前页面信息已失效",
							confirmButtonText: "重新加载",
							theme: "round-button",
						}).then(() => {
							uni.reLaunch({
								url: "/pages/SSOLogin"
							});
						})

					} else {
						Toast.clear()
						Toast('提交失败')
					}
				})
			}, 1200),
			postMessage() {
				let params = []
				this.surveyArr.forEach((item, index) => {
					params.push({
						objId: item.objId, // 勘察内容ID
						workPlanId: item.workPlanId, // 作业计划ID
						isStandard: item.isStandard, //是否标准（0：标准，1：非标准）
						situationDescription: item.situationDescription // 情况说明
					})
				})
				this.$apiRequest.bzhzyApi
					.modifySurverExecutionInfo(params)
					.then(res => {
						Toast.clear()
						Toast('提交成功')
						// if (this.curSort < this.recordData.length) {
						let index = this.recordData.findIndex(item => item.sort === this.curSort)
						if (this.selectIndex < this.recordData.length - 1) {
							this.selectIndex = index + 1
						} else {
							this.selectIndex = index
						}
						if (res.data.isFinsh) {
							Dialog.confirm({
									message: '是否确认提交，提交后不能修改',
									confirmButtonColor: '#417adc'
								})
								.then(() => {
									this.goSave()
								})
								.catch(() => {

								})
						}
						this.getSurverData()
						// }
					}).catch(error => {
						Toast.clear()
						Toast('提交失败')
					})
			},
			executeSubmit() {
				Toast.loading({
					duration: 0,
					message: '加载中...',
					forbidClick: true
				})
				this.handleDebGet()
			},
			imageHandle(imgIndex, imgItem, handleType, index) {
				this.surveyIndex = index
				if (handleType === 'CHOOSE') {
					// let base64List = []
					// let base64File =
					// 	""
					// let fileRaw = this.dataURLtoFile(base64File, "test.jpeg")
					// base64List.push({
					// 	raw: fileRaw,
					// 	img: base64File,
					// })
					// base64List.forEach(img => {
					// 	this.surveyArr[this.surveyIndex].file.push(img)
					// })

					this.choosePhoto()
				} else if (handleType === 'PREVIEW') {
					this.fileList = [imgItem]
					this.showPreview = true
				} else if (handleType === 'DELETE') {
					Dialog.confirm({
							message: '删除后不可恢复，是否确定删除？',
							confirmButtonColor: '#417adc'
						})
						.then(() => {
							this.deleteFileChange(imgIndex, imgItem, index)
						})
						.catch(() => {
							// on cancel
						})
				}
			},
			deleteFileChange(imgIndex, imgItem, index) {
				//本地上传-删除文件，raw=null 走删除文件接口
				if (imgItem.raw) {
					this.surveyArr[index].file.splice(imgIndex, 1)
				} else {
					this.deleteFile(imgItem, index, imgIndex)
				}
			},
			choosePhoto() {
				let _this = this
				//相册可选的数量
				let num = 0
				this.surveyArr[this.surveyIndex].file.forEach(item => {
					if (item.img) {
						num++
					}
				})
				let selectNum = this.wxCount - num
				console.log(selectNum, this.wxCount, num)
				wx.chooseImage({
					count: selectNum,
					sourceType: ['album', 'camera'],
					success: chooseImageRes => {
						_this.syncLocalImg(chooseImageRes.localIds)
						console.log("_this.base64List", _this.base64List)

					},
					fail: error => {
						console.log(error)
					}
				})
			},
			async syncLocalImg(localIds) {
				this.base64List = []
				console.log("localIds", localIds)
				for (let i = 0; i < localIds.length; i++) {
					await this.syncUpload(localIds[i], i, localIds.length)
				}
			},
			syncUpload(localId, i, localIdsLength) {
				let self = this;
				console.log("localId", localId)
				return new Promise(resolve => {
					wx.getLocalImgData({
						localId, // 图片的localID
						success: function(resBackData) {
							let localData = resBackData.localData;
							let imageBase64 = ''
							const photoName = `${new Date().getTime()}`
							//判断是否有这样的头部
							if (localData.indexOf('data:image') == 0) {
								//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
								imageBase64 = localData
							} else {
								//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
								//此时一个正常的base64图片路径就完美生成赋值到img的src中了
								imageBase64 =
									'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
							}
							//直接使用imageBase64展示，会导致swipe卡顿
							let file = self.dataURLtoFile(imageBase64,
								`${photoName}.jpeg`)
							let blob = self.h5_url_to_blob(imageBase64)
							self.base64List.push({
								raw: file,
								img: URL.createObjectURL(blob),
							})
							if (i + 1 === localIdsLength) {
								self.base64List.forEach(img => {
									self.surveyArr[self.surveyIndex].file.push(img)
								})
							}
							resolve("ok")
						}
					})
				})
			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], filename, {
					type: mime
				})
			},
			h5_url_to_blob(url) {
				let arr = url.split(',')
				let mime = arr[0].match(/:(.*?);/)[1]
				let bstr = atob(arr[1])
				let n = bstr.length
				let u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new Blob([u8arr], {
					type: mime
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	.save_btn {
		font-size: px2vw(54);
		margin-right: px2vw(40);
	}

	.container {
		display: flex;
		flex-direction: column;
		height: calc(100vh - #{px2vh(163)});
		// overflow: hidden;
		background: #f2f6fa;


		.title {
			padding: px2vh(30);
			// : 10px auto;

			.t-number {
				display: inline-block;
				width: px2vw(70);
				height: px2vw(70);
				border-radius: 50%;
				background: #417adc;
				color: #fff;
				font-weight: bold;
				text-align: center;
				line-height: px2vw(70);
				margin-right: px2vw(20);
			}
		}

		.card {
			flex: 1;
			overflow: scroll;
			margin-bottom: px2vh(180);

			.card-wrap {
				// height: 400px;
				margin: 0 px2vw(30) px2vh(30) px2vw(30);
				padding: px2vw(20);
				border-radius: px2vw(20);
				background: #fff;
			}
		}


		.w-row-1 {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #f7f7f7;
			min-height: px2vh(120);
			margin: px2vw(10);
			border-radius: px2vh(20);

			.row-l {
				display: flex;
				align-items: center;
				flex: 1;
				padding: 0 px2vw(10);

				img {
					width: px2vw(60);
					height: px2vw(60);
					margin: 0 px2vw(8);
				}

				span {
					margin: px2vw(10);
					// width: 154px;
					color: #417adc;
				}
			}
		}

		.w-row-2 {
			display: flex;
			align-items: center;
			justify-content: space-between;
			opacity: 0.8;
			font-size: px2vh(42);
			font-weight: 700;
			text-align: left;
			color: #666666;
			padding: px2vw(20);

			.r-l,
			.r-r {
				flex: 1;
				font-size: px2vw(42);

				span {
					color: #417adc;
				}
			}
		}

		.w-row-3 {
			margin: px2vh(12) 0;
			padding: px2vw(40);
			background: #f7f7f7;
			border-radius: px2vh(13);
			opacity: 0.7;
			font-size: px2vw(42);
			font-weight: 400;
			text-align: left;
			color: #666666;
		}

		.w-row-4 {
			padding: 0 px2vw(20);

			.r-4-label {
				font-size: px2vw(42);
				font-weight: 400;
				text-align: left;

				span {
					opacity: 0.7;
					color: #666666;
				}
			}
		}

		.w-row-5 {
			.r-5-label {
				font-size: px2vw(42);
				font-weight: 400;
				text-align: left;
			}

			.r-5-remark {
				min-height: px2vh(200);
				width: initial;
				padding: px2vh(40);
				background: #f7f7f7;
				border-radius: px2vh(20);
				margin: px2vh(20) 0 px2vh(40);
			}
		}

		.btn-container {
			margin: px2vh(80) px2vw(30);
			background: #f2f6fa;
			display: flex;
			justify-content: space-between;

			.van-button {
				height: px2vh(100);
				width: px2vw(450);
				border-radius: $border-radius-base;
			}
		}


	}

	.sub-btn-container {
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: px2vw(180);
		background: #f2f6fa;
		// padding-bottom: 100px;

		.submit-btn {
			margin: 0 px2vw(30);
			border-radius: px2vw(20);
		}
	}

	.image-wrap {
		width: 100%;
		height: px2vw(215);
		display: flex;
		margin: px2vw(49) auto;

		.image-list {
			width: 100%;
			display: flex;
			flex-wrap: wrap;

			img {
				width: px2vw(215);
				height: px2vw(215);
				margin-right: px2vw(40);
				border-radius: px2vw(6);
			}

			.upload-button {
				width: px2vw(215);
				height: px2vw(215);
				background-size: cover;
				position: relative;
				// background-image: url('../../../static/img/ywgj.png');
				margin-right: px2vw(40);

				.delete-icon {
					position: absolute;
					top: px2vw(-20);
					right: px2vw(-20);
					width: px2vw(40);
					height: px2vw(40);
					background-color: #ff4355;
					border-radius: 50%;
					color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}

	.directory {
		background: #fff;
		padding: px2vw(20) 0;
		overflow: auto;

		&::-webkit-scrollbar {
			width: 0 !important;
			height: 0 !important;
			display: none;
		}

		ul {
			display: inline-flex;
			padding-left: px2vw(30);

			li.li-number {
				display: inline-block;
				width: px2vw(70);
				height: px2vw(70);
				border-radius: 50%;
				background: #417adc;
				color: #fff;
				font-weight: bold;
				text-align: center;
				line-height: px2vw(70);
				margin-right: px2vw(20);

				&.active {
					background: #417adc !important;
				}

				&:last-child {
					margin-right: px2vw(40);
				}
			}
		}
	}

	.isrequired::before {
		content: '*';
		color: #ff4355;
		display: inline-block;
	}

	// 头部目录列表
	.directory {
		position: sticky;
		top: px2vh(0);
		z-index: 99;
		background: #fff;
		padding: px2vw(20) 0;
		overflow: auto;

		&::-webkit-scrollbar {
			width: 0 !important;
			height: 0 !important;
			display: none;
		}

		ul {
			display: inline-flex;
			padding-left: px2vw(30);

			li.li-number {
				display: inline-block;
				width: px2vw(70);
				height: px2vw(70);
				border-radius: 50%;
				background: #c9c9c9;
				color: #fff;
				// font-weight: bold;
				text-align: center;
				line-height: px2vw(70);
				margin-right: px2vw(30);

				&:last-child {
					margin-right: px2vw(40);
				}
			}
		}
	}

	.expand-ul {
		display: flex;
		flex-wrap: wrap;
		padding-right: px2vw(80);

		li {
			margin-bottom: px2vw(16);
		}
	}

	.expand-wrap {
		position: fixed;
		z-index: 99;
		right: 0;
		top: px2vh(163);
		width: px2vw(68);
		height: px2vw(120);
		line-height: px2vw(150);
		text-align: right;
		background: linear-gradient(-90deg, #ffffff 40%, rgba(255, 255, 255, 0) 100%);
		font-size: px2vw(18);
		padding-right: px2vw(20);
	}

	.van-preview-wrap {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;

		.van-swipe {
			width: 100%;
			height: 100%;

			.van-swipe-item {
				display: flex;

				img {
					width: 100%;
					height: 100%;
					object-fit: contain;
				}
			}
		}
	}

	.van-popup {
		background-color: rgba(0, 0, 0, 0.8);

		.van-cell {
			position: absolute;
			bottom: 0;
			border-top: 4px solid #eee;
			z-index: 3;
		}
	}
</style>
